package com.Guigu.AIchat.service;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.List;


@Component
public class DeepSeekService {
    
    @Value("${deepseek.api.key}")
    private String apiKey;
    
    @Value("${deepseek.api.url}")
    private String apiUrl;
    
    @Value("${deepseek.api.model}")
    private String model;
    
    private final WebClient webClient;
    
    public DeepSeekService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.build();
    }
    
    public String getChatResponse(String userMessage) {
        try {
            DeepSeekRequest request = new DeepSeekRequest(
                model,
                List.of(new Message("user", userMessage)),
                0.7,
                1024
            );
            
            DeepSeekResponse response = webClient.post()
                .uri(apiUrl)
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .bodyValue(request)
                .retrieve()
                .bodyToMono(DeepSeekResponse.class)
                .block();
            
            if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) {
                return response.getChoices().get(0).getMessage().getContent();
            }
            
            return "抱歉，未能获取到AI回复。";
            
        } catch (Exception e) {
            return "调用DeepSeek服务时出错: " + e.getMessage();
        }
    }
    
    // 请求和响应DTO类
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class DeepSeekRequest {
        private String model;
        private List<Message> messages;
        private double temperature;
        private int max_tokens;
    }
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Message {
        private String role;
        private String content;
    }
    
    @Data
    public static class DeepSeekResponse {
        private List<Choice> choices;
        
        @Data
        public static class Choice {
            private Message message;
        }
    }
}